import _ from 'lodash'
import validate from 'validate.js'

function validateImpl(event, {handler, value, name}, constraints) {
  console.log('Validate value', value)
  let validateAttributes = {}
  validateAttributes[name] = value
  let validateConstraints = {}
  validateConstraints[name] = constraints

  // 显示错误信息
  let validateMsg = validate(validateAttributes, validateConstraints)
  if (validateMsg && validateMsg[name] instanceof Array) {
    this.errorMsg = validateMsg[name].join('\n')
    this.showError = true
    if (handler instanceof Function) {
      handler(validateMsg)
    }
    setTimeout(() => {
      this.showError = false
    }, 2000)
  }
}

const ValidatorMixin = {
  data: function () {
    return {
      showError: false,
      errorMsg: null
    }
  },
  methods: {
    validate: _.debounce(validateImpl),
    validateImmediate: validateImpl
  }
}

const Validator = {
  install: function (Vue) {
    // 核心部分，在我们使用Vue.use()时，自动调用的是install，而install导出的必须是的组件
    Vue.mixin(ValidatorMixin)
    Vue.prototype.$validator = {
      showError: false,
      errorMsg: null
    }
  }
}

export default Validator
